<template>
  <view class="container">
        <u-form :model="form" ref="uForm" :rules="rules" label-width="120">
          <!-- 基本信息部分 -->
          <view class="form-section">
            <text class="section-title">基本信息</text>
            <u-form-item label="客户名称" prop="customerName">
              <u-input v-model="form.customerName" placeholder="请输入客户名称" />
            </u-form-item>
            <u-form-item label="联系人电话" prop="mainContactPhone">
              <u-input v-model="form.mainContactPhone" placeholder="请输入联系人电话" />
            </u-form-item>
            <u-form-item label="身份证号" prop="idCard">
              <u-input v-model="form.idCard" placeholder="请输入身份证号" />
            </u-form-item>
            <u-form-item label="客户来源" prop="customerSource">
              <uni-data-select v-model="form.customerSource" :localdata="sourceOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="婚姻状态" prop="maritalStatus">
              <uni-data-select v-model="form.maritalStatus" :localdata="maritalStatusOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="所在城市" prop="city">
              <u-input v-model="form.city" placeholder="请输入所在城市" />
            </u-form-item>
          </view>

          <!-- 贷款信息部分 -->
          <view class="form-section">
            <text class="section-title">贷款信息</text>
            <u-form-item label="意向产品" prop="intendedProduct">
              <u-input v-model="form.intendedProduct" placeholder="请输入意向产品" />
            </u-form-item>
            <u-form-item label="需求金额(万)" prop="requiredAmount">
              <u-input v-model="form.requiredAmount" placeholder="请输入需求金额" type="number" />
            </u-form-item>
            <u-form-item label="贷款用途" prop="loanPurpose">
              <uni-data-select v-model="form.loanPurpose" :localdata="loanPurposeOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="贷款期限(月)" prop="loanPeriod">
              <u-input v-model="form.loanPeriod" placeholder="请输入贷款期限" type="number" />
            </u-form-item>
            <u-form-item label="负债情况" prop="debtStatus">
              <uni-data-select v-model="form.debtStatus" :localdata="debtStatusOptions"></uni-data-select>
            </u-form-item>
          </view>

          <!-- 工作信息部分 -->
          <view class="form-section">
            <text class="section-title">工作信息</text>
            <u-form-item label="职业身份" prop="occupation">
              <uni-data-select v-model="form.occupation" :localdata="occupationOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="当前单位工龄(月)" prop="currentCompanyTenure">
              <u-input v-model="form.currentCompanyTenure" placeholder="请输入当前单位工龄" type="number" />
            </u-form-item>
            <u-form-item label="工资发放形式" prop="salaryPaymentMethod">
              <uni-data-select v-model="form.salaryPaymentMethod" :localdata="salaryPaymentOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="月收入(元)" prop="monthlyIncome">
              <u-input v-model="form.monthlyIncome" placeholder="请输入月收入" type="number" />
            </u-form-item>
            <u-form-item label="社保" prop="socialSecurity">
              <uni-data-select v-model="form.socialSecurity" :localdata="socialSecurityOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="公积金" prop="housingFund">
              <uni-data-select v-model="form.housingFund" :localdata="housingFundOptions"></uni-data-select>
            </u-form-item>
          </view>

          <!-- 资产信息部分 -->
          <view class="form-section">
            <text class="section-title">资产信息</text>
            <u-form-item label="房产情况" prop="houseStatus">
              <uni-data-select v-model="form.houseStatus" :localdata="houseStatusOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="车产情况" prop="carStatus">
              <uni-data-select v-model="form.carStatus" :localdata="carStatusOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="信用卡情况" prop="creditCardStatus">
              <uni-data-select v-model="form.creditCardStatus" :localdata="creditCardOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="芝麻分" prop="zhimaScore">
              <uni-data-select v-model="form.zhimaScore" :localdata="zhimaScoreOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="保险保单" prop="insurancePolicy">
              <uni-data-select v-model="form.insurancePolicy" :localdata="insurancePolicyOptions"></uni-data-select>
            </u-form-item>
          </view>

          <!-- 关联信息部分 -->
          <view class="form-section">
            <text class="section-title">关联信息</text>
            <u-form-item label="归属人" prop="belongTo" >
              <uni-data-select v-model="form.belongTo" :localdata="userOptions"></uni-data-select>
            </u-form-item>
            <u-form-item label="备注" prop="remark">
              <u-input v-model="form.remark" placeholder="请输入备注信息" type="textarea" rows="3" />
            </u-form-item>
          </view>

          <!-- 分步保存按钮 -->
          <view class="button-group">
   <!--         <u-button type="primary" @click="step1Save" :loading="step1Loading">
              {{ step1Loading ? '保存中...' : '1. 保存基本信息' }}
            </u-button>
            <u-button type="primary" @click="step2Save" :loading="step2Loading" :disabled="!basicInfoSaved">
              {{ step2Loading ? '保存中...' : '2. 保存贷款信息' }}
            </u-button>
            <u-button type="primary" @click="step3Save" :loading="step3Loading" :disabled="!loanInfoSaved">
              {{ step3Loading ? '保存中...' : '3. 保存工作信息' }}
            </u-button>
            <u-button type="primary" @click="step4Save" :loading="step4Loading" :disabled="!workInfoSaved">
              {{ step4Loading ? '保存中...' : '4. 保存资产信息' }}
            </u-button>
            <u-button type="primary" @click="step5Save" :loading="step5Loading" :disabled="!assetInfoSaved">
              {{ step5Loading ? '保存中...' : '5. 保存关联信息' }}
            </u-button> -->
          
            <u-button type="success" @click="saveAll" :loading="savingAll">
              {{ savingAll ? '保存中...' : '保存全部' }}
            </u-button>
			<u-button @click="goUpload" type="warning">
			  资料上传
			</u-button>
            <u-button @click="navigateBack">返回</u-button>
          </view>
        </u-form>
  </view>
</template>

<script>
import { store } from '@/uni_modules/uni-id-pages/common/store.js'
const Odb=uniCloud.importObject('mydb-customer')
let eventChannel=null
export default {
  data() {
    return {
      customerId: null,
	    customer:null,
      form: {
        customerId: '',
        // 基本信息
        customerName: '',
        mainContactPhone: '',
        idCard: '',
        customerSource: '',
        maritalStatus: '',
        city: '',
        // 贷款信息
        intendedProduct: '',
        requiredAmount: '',
        loanPurpose: '',
        loanPeriod: '',
        debtStatus: '',
        // 工作信息
        occupation: '',
        currentCompanyTenure: '',
        salaryPaymentMethod: '',
        monthlyIncome: '',
        socialSecurity: '',
        housingFund: '',
        // 资产信息
        houseStatus: '',
        carStatus: '',
        creditCardStatus: '',
        zhimaScore: '',
        insurancePolicy: '',
        // 关联信息
        belongTo: '',
        remark: ''
      },
      // 验证规则
      rules: {
        customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
        // phone: [
        //   { required: true, message: '请输入手机号', trigger: 'blur' },
        //   { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        // ],
        // belongTo: [{ required: true, message: '请选择归属人', trigger: 'change' }]
      },
      // 选项数据
      sourceOptions: [],
      maritalStatusOptions: [],
      loanPurposeOptions: [],
      debtStatusOptions: [],
      occupationOptions: [],
      salaryPaymentOptions: [],
      socialSecurityOptions: [],
      housingFundOptions: [],
      houseStatusOptions: [],
      carStatusOptions: [],
      creditCardOptions: [],
      zhimaScoreOptions: [],
      insurancePolicyOptions: [],
      userOptions: [],
      // 分步保存状态
      step1Loading: false,
      step2Loading: false,
      step3Loading: false,
      step4Loading: false,
      step5Loading: false,
      savingAll: false,
      basicInfoSaved: false,
      loanInfoSaved: false,
      workInfoSaved: false,
      assetInfoSaved: false,
      allInfoSaved: false,
      eventChannel: null
    }
  },
  computed: {
    userInfo() {
      return store.userInfo
    }
  },
  onReady() {
  		//onReady 为uni-app支持的生命周期之一
      	this.$refs.uForm.setRules(this.rules)
  },

  onLoad(options) {
    this.eventChannel = this.getOpenerEventChannel();
    if (options.id) {
      this.customerId = options.id
	  this.loadCustomerData()
      this.loadCustomerMoreData()
    }
	this.loadOptions()
    this.loadUserOptions()
  },
  methods: {
	  loadOptions(){
	  	Odb.getOptions().then((res)=>{
	  		for (var key in res) {
	  			if (res.hasOwnProperty(key) && this[key]) {
	  				this[key] = res[key]
	  			}
	  		}
	  	})
	  },
	  async loadCustomerData() {
	    const db = uniCloud.database()
	    const res = await db.collection('mydb-customer').doc(this.customerId).get()
	    if (res.result.data.length > 0) {
	      this.customer = res.result.data[0]
		  this.form.phone=this.customer.phone
		  this.form.belongTo=this.customer.associated_users
		  this.form.mainContactPhone=this.customer.phone
		  this.form.customerName=this.customer.name
	    }
	  },
    // 加载用户选项
    async loadUserOptions() {
      try {
        const db = uniCloud.database()
        const res = await db.collection('uni-id-users').field("nickname,_id").get()
        this.userOptions = res.result.data.map(user => {
          return {
            text: user.nickname,
            value: user._id
          }
        })
        // 默认选择当前用户
        if (!this.customerId && this.userOptions.length > 0) {
          const currentUser = this.userOptions.find(user => user.value === this.userInfo._id)
          if (currentUser) {
            this.form.belongTo = currentUser.value
          } else if (this.userOptions.length > 0) {
            this.form.belongTo = this.userOptions[0].value
          }
        }
      } catch (error) {
        console.error('加载用户选项失败：', error)
        uni.showToast({ title: '加载用户选项失败', icon: 'none' })
      }
    },

    // 加载客户数据
    async loadCustomerMoreData() {
      try {
        const db = uniCloud.database()
        const res = await db.collection('mydb-customer-fields').where({customerId:this.customerId}).get()
        if (res.result.data.length > 0) {
          const customerData = res.result.data[0]
          for (var key in customerData) {
            if (customerData.hasOwnProperty(key) && this.form.hasOwnProperty(key)) {
              this.form[key] = customerData[key] || ''
            }
          }
          // 标记所有信息已保存
          this.basicInfoSaved = true
          this.loanInfoSaved = true
          this.workInfoSaved = true
          this.assetInfoSaved = true
          this.allInfoSaved = true
        }
      } catch (error) {
        console.error('加载客户数据失败：', error)
        uni.showToast({ title: '加载客户数据失败', icon: 'none' })
      }
    },

    // 第一步：保存基本信息
    async step1Save() {
      try {
          this.step1Loading = true
          const db = uniCloud.database()
          
          const basicInfo = {
            customerName: this.form.customerName,
            phone: this.form.phone,
            idCard: this.form.idCard,
            customerSource: this.form.customerSource,
            maritalStatus: this.form.maritalStatus,
            city: this.form.city,
            update_date: Date.now()
          }
          
          if (!this.customerId) {
            // 新增客户
            basicInfo.create_date = Date.now()
            basicInfo.createBy = this.userInfo._id
            const addResult = await db.collection('mydb-customer-fields').add(basicInfo)
            this.customerId = addResult.result._id
          } else {
            // 更新客户基本信息
            basicInfo.lastUpdateBy = this.userInfo._id
            await db.collection('mydb-customer-fields').where({customerName:this.customerId}).update(basicInfo)
          }
          
          this.basicInfoSaved = true
          uni.showToast({ title: '基本信息保存成功' })
      } catch (error) {
        console.error('保存基本信息失败：', error)
        uni.showToast({ title: '保存基本信息失败', icon: 'none' })
      } finally {
        this.step1Loading = false
      }
    },

    // 第二步：保存贷款信息
    async step2Save() {
      if (!this.basicInfoSaved) {
        uni.showToast({ title: '请先保存基本信息', icon: 'none' })
        return
      }
      
      try {
        this.step2Loading = true
        const db = uniCloud.database()
        
        const loanInfo = {
          intendedProduct: this.form.intendedProduct,
          requiredAmount: this.form.requiredAmount,
          loanPurpose: this.form.loanPurpose,
          loanPeriod: this.form.loanPeriod,
          debtStatus: this.form.debtStatus,
          lastUpdateBy: this.userInfo._id,
          update_date: Date.now()
        }
        
        await db.collection('mydb-customer-fields').where({customerName:this.customerId}).update(loanInfo)
        this.loanInfoSaved = true
        uni.showToast({ title: '贷款信息保存成功' })
      } catch (error) {
        console.error('保存贷款信息失败：', error)
        uni.showToast({ title: '保存贷款信息失败', icon: 'none' })
      } finally {
        this.step2Loading = false
      }
    },

    // 第三步：保存工作信息
    async step3Save() {
      if (!this.loanInfoSaved) {
        uni.showToast({ title: '请先保存贷款信息', icon: 'none' })
        return
      }
      
      try {
        this.step3Loading = true
        const db = uniCloud.database()
        
        const workInfo = {
          occupation: this.form.occupation,
          currentCompanyTenure: this.form.currentCompanyTenure,
          salaryPaymentMethod: this.form.salaryPaymentMethod,
          monthlyIncome: this.form.monthlyIncome,
          socialSecurity: this.form.socialSecurity,
          housingFund: this.form.housingFund,
          lastUpdateBy: this.userInfo._id,
          update_date: Date.now()
        }
        
        await db.collection('mydb-customer-fields').where({customerName:this.customerId}).update(workInfo)
        this.workInfoSaved = true
        uni.showToast({ title: '工作信息保存成功' })
      } catch (error) {
        console.error('保存工作信息失败：', error)
        uni.showToast({ title: '保存工作信息失败', icon: 'none' })
      } finally {
        this.step3Loading = false
      }
    },

    // 第四步：保存资产信息
    async step4Save() {
      if (!this.workInfoSaved) {
        uni.showToast({ title: '请先保存工作信息', icon: 'none' })
        return
      }
      
      try {
        this.step4Loading = true
        const db = uniCloud.database()
        
        const assetInfo = {
          houseStatus: this.form.houseStatus,
          carStatus: this.form.carStatus,
          creditCardStatus: this.form.creditCardStatus,
          zhimaScore: this.form.zhimaScore,
          insurancePolicy: this.form.insurancePolicy,
          lastUpdateBy: this.userInfo._id,
          update_date: Date.now()
        }
        
        await db.collection('mydb-customer-fields').where({customerName:this.customerId}).update(assetInfo)
        this.assetInfoSaved = true
        uni.showToast({ title: '资产信息保存成功' })
      } catch (error) {
        console.error('保存资产信息失败：', error)
        uni.showToast({ title: '保存资产信息失败', icon: 'none' })
      } finally {
        this.step4Loading = false
      }
    },

    // 第五步：保存关联信息
    async step5Save() {
      if (!this.assetInfoSaved) {
        uni.showToast({ title: '请先保存资产信息', icon: 'none' })
        return
      }
      
      try {
        // 验证归属人
        const validResult = await this.$refs.uForm.validateFields(['belongTo'])
        
        if (validResult) {
          this.step5Loading = true
          const db = uniCloud.database()
          
          const relatedInfo = {
            belongTo: this.form.belongTo,
            remark: this.form.remark,
            lastUpdateBy: this.userInfo._id,
            update_date: Date.now()
          }
          
          await db.collection('mydb-customer-fields').where({customerName:this.customerId}).update(relatedInfo)
          this.allInfoSaved = true
          uni.showToast({ title: '关联信息保存成功，所有信息已完成' })
        }
      } catch (error) {
        console.error('保存关联信息失败：', error)
        uni.showToast({ title: '保存关联信息失败', icon: 'none' })
      } finally {
        this.step5Loading = false
      }
    },

    // 保存全部信息
    async saveAll() {
      try {
        this.savingAll = true
        // 验证必填字段
        const validResult = await this.$refs.uForm.validate()
        
        if (validResult) {
          const db = uniCloud.database()
          // 整合所有信息
          const allInfo = {
            ...this.form,
            // 时间和操作人信息
            lastUpdateBy: this.userInfo._id,
            updateTime: Date.now()
          }
          if (!this.form.customerId) {
            // 创建新记录
			allInfo.customerId=this.customerId
            await db.collection('mydb-customer-fields').add(allInfo)
          } else {
            // 更新客户信息
            await db.collection('mydb-customer-fields').where({customerId:this.customerId}).update(allInfo)
          }
          
          // 标记所有步骤已完成
          this.basicInfoSaved = true
          this.loanInfoSaved = true
          this.workInfoSaved = true
          this.assetInfoSaved = true
          this.allInfoSaved = true
          
          uni.showToast({ title: '保存成功' })
        }
      } catch (error) {
        console.error('保存全部信息失败：', error)
        uni.showToast({ title: '保存全部信息失败', icon: 'none' })
      } finally {
        this.savingAll = false
      }
    },
    // 资料上传
    goUpload() {
      uni.navigateTo({
        url: '/pages/customer/upload?customerId=' + this.customerId
      })
    },
    // 返回上一页
    navigateBack() {
      if (this.eventChannel) {
        this.eventChannel.emit('refresh', null)
      }
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.form-section {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 4rpx solid #007aff;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 30rpx;
}

.button-group u-button {
  width: 100%;
}
</style>